package org.putrpctorest.parameter.impl;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

public class Expression {

	private org.springframework.expression.Expression compiledTargetExpression;
	private org.springframework.expression.Expression compiledSourceExpression;
	private Class<?> targetType;

	public Expression(Class<?> targetType, String targetExpression,
			String sourceExpression) {
		ExpressionParser expParser = new SpelExpressionParser();

		compiledTargetExpression = expParser.parseExpression(targetExpression);
		compiledSourceExpression = expParser.parseExpression(sourceExpression);
		this.targetType = targetType;
	}

	public void eval(EvaluationContext ctx) {

		compiledTargetExpression.setValue(ctx,
				compiledSourceExpression.getValue(ctx, targetType));

	}
	
	public String getTarget() {
		return compiledTargetExpression.getExpressionString();
	}

	public String getSource() {
		return compiledSourceExpression.getExpressionString();
	}

	@Override
	public String toString() {
		return "[" + compiledTargetExpression.getExpressionString() + "="
				+ compiledSourceExpression.getExpressionString() + "]";
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Expression other = (Expression) obj;
		if (compiledSourceExpression == null) {
			if (other.compiledSourceExpression != null)
				return false;
		} else if (!compiledSourceExpression.getExpressionString()
				.equals(other.compiledSourceExpression.getExpressionString()))
			return false;
		if (compiledTargetExpression == null) {
			if (other.compiledTargetExpression != null)
				return false;
		} else if (!compiledTargetExpression.getExpressionString()
				.equals(other.compiledTargetExpression.getExpressionString()))
			return false;
		if (targetType == null) {
			if (other.targetType != null)
				return false;
		} else if (!targetType.equals(other.targetType))
			return false;
		return true;
	}
	
	

}
